import commonFun from './common.js' //公共方法
import Store from '../../store/index.js' //公共方法

function fetch(method, url, data) {
	return new Promise((resolve, reject) => {
		// console.log(commonFun.baseURL + url);
		// console.log('token ' + commonFun.getUserToken());
		//发起请求
		// console.log(Store);
		uni.request({
			url: commonFun.baseURL + 'api/' + url,
			data: data,
			method: method,
			header: {
				'content-type': 'application/json', //自定义请求头信息
				'X-TOKEN': commonFun.getUserToken(),
				'X-AuthType': Store.state.standing == 'user' ? 2 : 1,//0：后台用户登录，1：小程序端管理员登录2：小程序端用户登录
			},
			success: (res) => {
				// console.log(res);
				resolve(res.data)
				//用户token失效或用户被禁言等
				if (res.data.code == 4001) {
					commonFun.toast(res.data.message);
					commonFun.clearUserInfo();
				}
			},
			fail: err => {
				reject(err)
			}
		});
	})
}

export default {
	get: function (url, params = {}) {
		return fetch('GET', url, params)
	},
	post: function (url, params = {}) {
		return fetch('POST', url, params)
	},
	put: function (url, params = {}) {
		return fetch('PUT', url, params)
	},
	delete: function (url, params = {}) {
		return fetch('DELETE', url, params)
	},
	uploadFile(file, formData) {
		console.log(formData);
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: commonFun.baseURL + 'api/mobile/upload/up',
				filePath: file,
				fileType: 'image',
				name: 'file',
				formData: formData,
				header: {
					// 'content-type': 'application/json', //自定义请求头信息
					'X-TOKEN': commonFun.getUserToken(),
					'X-AuthType': Store.state.standing == 'user' ? 2 : 1,//0：后台用户登录，1：小程序端管理员登录2：小程序端用户登录
				},
				success: (res) => {
					resolve(JSON.parse(res.data))
				},
				fail: err => {
					reject(err)
				}
			});
		})
	},
}